import goodsApi from '@/api/goods-management/goods'
import goodsSql from '@/sql/goods/index'
import { getToken, setToken } from '@/utils/token'
import { _openid } from '@/api/config/appconfig'
import { SecretKey, SecretId, Bucket, Region } from '@/api/config/tencent-yum'
import COS from 'cos-js-sdk-v5'
const state = {
  // access_token
  access_token: getToken(),
  // 商品类型列表
  goodsTypeList: [],
  // 商品列表
  goodsList: [],
  // 商品sku列表
  goodsSkuList: [],
  // 商品上架列表
  goodsShelves: []
}
const mutations = {
  setAccessToken: (state, access_token) => {
    state.access_token = access_token
  },
  setGoodsShelves: (state, goodsShelves) => {
    state.goodsShelves = goodsShelves
  },
  setGoodsTypeList: (state, goodsTypeList) => {
    state.goodsTypeList = goodsTypeList
  },
  setGoodsSkuList: (state, goodsSkuList) => {
    state.goodsSkuList = goodsSkuList
  },
  saveAccessTokenToState: (state, access_token) => {
    state = access_token
  },
  setGoodsList: (state, goodsList) => {
    state.goodsList = goodsList
  }
}
const actions = {
  // 获取access_token
  getAccess_token({ commit }) {
    goodsApi.getAccess_token().then(res => {
      console.log(234)
      commit('setAccessToken', res.access_token)
      setToken(res.access_token)
    })
  },
  // 添加商品类型
  addGoodsType({ state, dispatch }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_type").add({
            data:[
               {
                   _openid: "${_openid}",
                   parent_id: "${formData.parent_id}",
                   type_name: "${formData.type_name}",
                   sort: ${formData.sort},
                   level: ${formData.level},
                   create_time: new Date(),
                   update_time: new Date(),
                   is_has_child: 0
               }
            ]
        })`
    return new Promise((resolve, reject) => {
      goodsApi.add(state.access_token, goodsSql.recordSql).then(res => {
        dispatch('updateGoodsTypeChild', formData)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 更新是否有孩子节点
  updateGoodsTypeChild({ dispatch }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_type").doc("${formData.parent_id}").update(
      {
          data:{
            is_has_child: ${formData.parent_is_has_child},
          }})`
    const updateGoodsTypeChildSql = { ...goodsSql.recordSql }
    return dispatch('promiseUpdateRequest', updateGoodsTypeChildSql)
  },
  // 更新商品类型
  updateGoodsType({ dispatch }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_type").doc("${formData._id}").update(
            {
                data:{
                    sort: ${formData.sort},
                    parent_id: "${formData.parent_id}",
                    level: ${formData.level},
                    update_time: new Date(),
                    type_name: "${formData.type_name}"
                }})`
    return dispatch('promiseUpdateRequest', goodsSql.recordSql)
  },
  // 单一删除商品类型
  deleteGoodsTypeById({ state }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_type").doc("${formData._id}").remove()`
    return new Promise((resolve, reject) => {
      goodsApi.delete(state.access_token, goodsSql.recordSql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 批量删除商品类型
  deleteGoodsTypeByIds({ state }, formDatas) {
    const promiseArr = []
    formDatas.forEach(element => {
      goodsSql.recordSql.query = `db.collection("goods_type").doc("${element._id}").remove()`
      // 使用临时变量存储,因为goodsSql是一个对象后面的修改会影响覆盖前面的数据
      const deleteGoodsTypeByIdSql = { ...goodsSql.recordSql }
      promiseArr.push(new Promise((resolve, reject) => {
        goodsApi.delete(state.access_token, deleteGoodsTypeByIdSql).then(res => {
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      }))
    })
    return Promise.all(promiseArr)
  },
  // 获取商品类型列表记录
  getGoodsTypes({ dispatch, state }) {
    const data = {
      requestName: 'getGoodsTypeList'
    }
    return new Promise((resolve, reject) => {
      goodsApi.invokeCloudFunction(state.access_token, data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 联表获取商品列表
  getGoodsListLinkGoodsType({ state }) {
    const data = {
      requestName: 'getGoodsList'
    }
    return new Promise((resolve, reject) => {
      goodsApi.invokeCloudFunction(state.access_token, data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 搜索商品
  searchGoods({ state }, formData) {
    console.log(formData)
    const data = {
      requestName: 'searchGoodsSpu',
      data: formData
    }
    return new Promise((resolve, reject) => {
      goodsApi.invokeCloudFunction(state.access_token, data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 搜索Sku商品
  searchGoodsSku({ state }, formData) {
    console.log(formData)
    const data = {
      requestName: 'searchGoodsSku',
      data: formData
    }
    return new Promise((resolve, reject) => {
      goodsApi.invokeCloudFunction(state.access_token, data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 添加商品
  addGoods({ state }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_spu").add({
      data:[
         {
             _openid: "${_openid}",
             detail: "${formData.detail}",
             detail_images_url: ${JSON.stringify(formData.detail_images_url)},
             goods_brief: "${formData.goods_brief}",
             goods_image: {
               main_image_url: ${JSON.stringify(formData.main_image_url)},
               secondary_images_url: ${JSON.stringify(formData.secondary_images_url)}
             },
             goods_name: "${formData.goods_name}",
             goods_no: "${formData.goods_no}",
             key_words: "${formData.key_words}",
             low_price: "${formData.low_price}",
             specification: [],
             recommend: 0,
             goods_status: 0,
             type_id: "${formData.type_id}",
             create_time: new Date(),
             update_time: new Date()
         }
      ]
  })`
    return new Promise((resolve, reject) => {
      goodsApi.add(state.access_token, goodsSql.recordSql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 修改商品
  updateGoods({ state }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_spu").doc("${formData._id}").update(
      {
          data:{
            _openid: "${_openid}",
            detail: "${formData.detail}",
            detail_images_url: ${JSON.stringify(formData.detail_images_url)},
            goods_brief: "${formData.goods_brief}",
            goods_image: {
              main_image_url: ${JSON.stringify(formData.main_image_url)},
              secondary_images_url: ${JSON.stringify(formData.secondary_images_url)}
            },
            goods_name: "${formData.goods_name}",
            key_words: "${formData.key_words}",
            low_price: "${formData.low_price}",
            type_id: "${formData.type_id}",
            update_time: new Date()
          }})`
    return new Promise((resolve, reject) => {
      goodsApi.update(state.access_token, goodsSql.recordSql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 删除商品
  deleteGoodsById({ state }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_spu").doc("${formData._id}").remove()`
    return new Promise((resolve, reject) => {
      goodsApi.delete(state.access_token, goodsSql.recordSql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 批量删除商品
  deleteGoodsByIds({ state }, formDatas) {
    const promiseArr = []
    formDatas.forEach(element => {
      goodsSql.recordSql.query = `db.collection("goods_spu").doc("${element._id}").remove()`
      // 使用临时变量存储,因为goodsSql是一个对象后面的修改会影响覆盖前面的数据(浅拷贝)
      const deleteGoodsTypeByIdSql = { ...goodsSql.recordSql }
      promiseArr.push(new Promise((resolve, reject) => {
        goodsApi.delete(state.access_token, deleteGoodsTypeByIdSql).then(res => {
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      }))
    })
    return Promise.all(promiseArr)
  },
  // 商品上下架
  updateGoodsStatus({ state }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_spu").doc("${formData._id}").update(
      {
          data:{
            _openid: "${_openid}",
            goods_status: ${formData.goods_status},
            update_time: new Date()
          }})`
    return new Promise((resolve, reject) => {
      goodsApi.update(state.access_token, goodsSql.recordSql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 批量商品上下架
  updateGoodsStatusMore({ state }, data) {
    const { formDatas, goods_status } = data
    const promiseArr = []
    formDatas.forEach(element => {
      goodsSql.recordSql.query = `db.collection("goods_spu").doc("${element._id}").update(
        {
            data:{
              _openid: "${_openid}",
              goods_status: ${goods_status},
              update_time: new Date()
            }})`
      // 使用临时变量存储,因为goodsSql是一个对象后面的修改会影响覆盖前面的数据(浅拷贝)
      const deleteGoodsTypeByIdSql = { ...goodsSql.recordSql }
      promiseArr.push(new Promise((resolve, reject) => {
        goodsApi.update(state.access_token, deleteGoodsTypeByIdSql).then(res => {
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      }))
    })
    return Promise.all(promiseArr)
  },
  // 商品推荐与取消
  updateGoodsRecommend({ state }, data) {
    const { formData, recommendStatus } = data
    goodsSql.recordSql.query = `db.collection("goods_spu").doc("${formData._id}").update(
      {
          data:{
            _openid: "${_openid}",
            recommend: ${recommendStatus},
            update_time: new Date()
          }})`
    return new Promise((resolve, reject) => {
      goodsApi.update(state.access_token, goodsSql.recordSql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 商品的规格修改
  updateGoodsSpecification({ state }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_spu").doc("${formData._id}").update(
      {
          data:{
            _openid: "${_openid}",
            specification: ${JSON.stringify(formData.specification)},
            update_time: new Date()
          }})`
    return new Promise((resolve, reject) => {
      goodsApi.update(state.access_token, goodsSql.recordSql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 联表获取商品sku列表
  getGoodsSkus({ state }) {
    const data = {
      requestName: 'getGoodsSkuList'
    }
    return new Promise((resolve, reject) => {
      goodsApi.invokeCloudFunction(state.access_token, data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取商品的上下架列表
  getGoodsListLinkGoodsSku({ state }) {
    const data = {
      requestName: 'getGoodsListLinkGoodsSku'
    }
    return new Promise((resolve, reject) => {
      goodsApi.invokeCloudFunction(state.access_token, data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  searchGoodsShelves({ state }, formData) {
    const data = {
      requestName: 'searchGoodsShelves',
      data: formData
    }
    return new Promise((resolve, reject) => {
      goodsApi.invokeCloudFunction(state.access_token, data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  promiseGetRequest({ state }, sql) {
    return new Promise((resolve, reject) => {
      goodsApi.get(state.access_token, sql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  promiseUpdateRequest({ state }, sql) {
    return new Promise((resolve, reject) => {
      goodsApi.update(state.access_token, sql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  promiseAddRequest({ state }, sql) {
    return new Promise((resolve, reject) => {
      goodsApi.add(state.access_token, sql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  promiseDeleteRequest({ state }, sql) {
    return new Promise((resolve, reject) => {
      goodsApi.delete(state.access_token, sql).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 搜索商品通过商品编号
  getGoodsByGoodsNo({ dispatch }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_spu").where({
      goods_no: "${formData.goods_no}"
    }).get()`
    return dispatch('promiseGetRequest', goodsSql.recordSql)
  },
  // 添加商品sku
  addGoodsSku({ dispatch }, formData) {
    return new Promise((resolve, reject) => {
      dispatch('checkGoodsSku', formData).then(res => {
        if (res.data.length === 0) {
          goodsSql.recordSql.query = `db.collection("goods_sku").add({
            data:[
               {
                   _openid: "${_openid}",
                   goods_spu_id: "${formData.goods_spu_id}",
                   price: ${formData.price},
                   repertory: ${formData.repertory},
                   sku_name: "${formData.sku_name}",
                   sku_no: "${formData.sku_no}",
                   specification_select: ${JSON.stringify(formData.specification_select)},
                   create_time: new Date(),
                   update_time: new Date()
               }
            ]
        })`
          dispatch('promiseAddRequest', goodsSql.recordSql).then(res => {
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        } else {
          resolve({
            errcode: 500,
            errmsg: '商品sku已存在'
          })
        }
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 检查商品sku是否存在
  checkGoodsSku({ dispatch }, formData) {
    console.log(formData)
    goodsSql.recordSql.query = `db.collection("goods_sku").where({
      goods_spu_id: "${formData.goods_spu_id}",
      specification_select: ${JSON.stringify(formData.specification_select)}
    }).get()`
    return dispatch('promiseGetRequest', goodsSql.recordSql)
  },
  // 修改商品sku
  updateGoodsSku({ dispatch }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_sku").doc("${formData._id}").update(
      {
          data:{
            _openid: "${_openid}",
            specification_select: ${JSON.stringify(formData.specification_select)},
            price: ${formData.price},
            repertory: ${formData.repertory},
            update_time: new Date()
          }})`
    return dispatch('promiseUpdateRequest', goodsSql.recordSql)
  },
  // 删除商品sku
  deleteGoodsSkuById({ dispatch }, formData) {
    goodsSql.recordSql.query = `db.collection("goods_sku").doc("${formData._id}").remove()`
    return dispatch('promiseDeleteRequest', goodsSql.recordSql)
  },
  // 批量删除商品sku
  deleteGoodsSkuByIds({ state }, formDatas) {
    const promiseArr = []
    formDatas.forEach(element => {
      goodsSql.recordSql.query = `db.collection("goods_sku").doc("${element._id}").remove()`
      // 使用临时变量存储,因为goodsSql是一个对象后面的修改会影响覆盖前面的数据(浅拷贝)
      const deleteGoodsTypeByIdSql = { ...goodsSql.recordSql }
      promiseArr.push(new Promise((resolve, reject) => {
        goodsApi.delete(state.access_token, deleteGoodsTypeByIdSql).then(res => {
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      }))
    })
    return Promise.all(promiseArr)
  },
  // 上传图片
  // eslint-disable-next-line no-empty-pattern
  uploadFile({}, param) {
    return new Promise((resolve, reject) => {
      var cos = new COS({
        SecretId: SecretId,
        SecretKey: SecretKey
      })
      cos.putObject({
        Bucket: Bucket,
        Region: Region,
        /* 名字获取数组下标*/
        Key: `goods/${param.name}`,
        StorageClass: 'STANDARD',
        Body: param // 上传文件对象(通过下标获取)
      }, function(err, data) {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
  },
  // 删除图片
  // eslint-disable-next-line no-empty-pattern
  deleteFile({ }, param) {
    return new Promise((resolve, reject) => {
      var cos = new COS({
        SecretId: SecretId,
        SecretKey: SecretKey
      })
      cos.deleteObject({
        Bucket: Bucket,
        Region: Region,
        /* 名字获取数组下标*/
        Key: `goods/${param.name}`
      }, function(err, data) {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
  }
}
export default {
  state,
  mutations,
  actions
}
